<?php

/**
 * 依赖注入
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-05-31
 */

namespace fw\di;

class DI
{
    protected $_service = [];

    protected $_instances = [];

    public function set($name, $definition)
    {
        $this->_service[$name] = $definition;
    }

    public function get($name)
    {
        if (!isset($this->_service[$name])) {
            throw new Exception("`" . $name . "`wasn't found in the DI.");
        }

        if (!is_object($this->service[$name])) {
            throw new Exception("DI::set error.");
        }

        $definition = $this->service[$name];
        $instance = call_user_func($definition);

        return $instance;
    }

    public function getShare($name)
    {
        if (is_null($this->_instances[$name])) {
            $this->_instances[$name] = $this->get($name);
        }

        return $this->_instances[$name];
    }
}
